package com.xl.cloud.netty.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author XiangLiang
 * @Since 2025/1/9 9:20
 * @Description: BIOServer类
 */
public class BIOServer {
    public static void main(String[] args) throws IOException {
        // 线程池机制 思路
        // 1. 创建一个线程池
        // 2. 如果有新的客户端接入，就创建一个线程与之通讯（单独方法）
        ExecutorService threadPool = Executors.newCachedThreadPool();

        // 创建ServerSocket
        int port = 6666;
        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("服务器启动于" + port + "端口...");

        while (true) {
            System.out.println("线程信息1：Id = " + Thread.currentThread().getId()
                    + ", Name = " + Thread.currentThread().getName());
            // 监听，等待客户端连接
            System.out.println("等待连接...");
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");

            // 创建一个线程与之通讯
            threadPool.execute(() -> handle(socket));
        }
    }

    /**
     * 和客户端通讯
     *
     * @param socket 客户端连接对应的Socket
     */
    public static void handle(Socket socket) {
        try {
            System.out.println("线程信息2：Id = " + Thread.currentThread().getId()
                    + ", Name = " + Thread.currentThread().getName());
            byte[] bytes = new byte[1024];

            // 通过socket获取输入流
            InputStream inputStream = socket.getInputStream();

            // 循环的读取客户端发送的数据
            while (true) {
                System.out.println("线程信息3：Id = " + Thread.currentThread().getId()
                        + ", Name = " + Thread.currentThread().getName());

                System.out.println("read...");
                // 读入字节总数
                int length = inputStream.read(bytes);
                if (length != -1) {
                    System.out.println(new String(bytes, 0, length));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭和客户端的连接");
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
